package com.wwg.wechatrecord;

import static android.view.View.INVISIBLE;

import android.Manifest;
import android.os.Message;
import android.text.format.DateFormat;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatSeekBar;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.LinearLayoutCompat;

import com.blankj.utilcode.util.TimeUtils;
import com.freedom.lauzy.playpauseviewlib.PlayPauseView;
import com.kongzue.baseframework.BaseActivity;
import com.kongzue.baseframework.interfaces.DarkStatusBarTheme;
import com.kongzue.baseframework.interfaces.Layout;
import com.kongzue.baseframework.interfaces.NavigationBarBackgroundColorHex;
import com.kongzue.baseframework.util.JumpParameter;
import com.kongzue.baseframework.util.OnPermissionResponseListener;
import com.lzx.starrysky.OnPlayProgressListener;
import com.lzx.starrysky.OnPlayerEventListener;
import com.lzx.starrysky.SongInfo;
import com.lzx.starrysky.StarrySky;
import com.lzx.starrysky.control.RepeatMode;
import com.lzx.starrysky.manager.PlaybackStage;
import com.lzx.starrysky.utils.MD5;
import com.wwg.mp3record.MP3RecordStateView;
import com.wwg.mp3record.MP3Recorder;
import com.wwg.mp3record.OnRecordListener;
import com.wwg.mp3record.util.LogUtils;
import com.wwg.wechatrecord.utils.FilePath;

import java.util.Calendar;
import java.util.Date;

@Layout(R.layout.activity_main)
@DarkStatusBarTheme(true)
@NavigationBarBackgroundColorHex("#00000000")
public class MainActivity extends BaseActivity {

    private LinearLayoutCompat audioMsgLayout;
    private AppCompatTextView filePath;
    private AppCompatTextView fileTime;
    private AppCompatSeekBar seek;
    private AppCompatTextView playTime;
    private AppCompatTextView mediaTime;
    private PlayPauseView ctrl;
    private AppCompatButton recordAudio;
    private MP3RecordStateView recordStateView;

    //当亲是否正在按压
    private boolean isOnTouch = false;
    //点击时间间隔控制参数，防止快速点击造成录音异常
    private long time;

    //音频文件名
    private String audioName = "";
    //音频信息
    private SongInfo songInfo;

    //用户是否正在拖拽进度条
    private boolean isUserCtrlSeek = false;

    //是否刚准备好音频
    private boolean isJustPrepare = true;

    @Override
    public void initViews() {

        audioMsgLayout = (LinearLayoutCompat) findViewById(R.id.audioMsg_Layout);
        filePath = (AppCompatTextView) findViewById(R.id.filePath);
        fileTime = (AppCompatTextView) findViewById(R.id.fileTime);
        seek = (AppCompatSeekBar) findViewById(R.id.seek);
        playTime = (AppCompatTextView) findViewById(R.id.playTime);
        mediaTime = (AppCompatTextView) findViewById(R.id.media_time);
        ctrl = (PlayPauseView) findViewById(R.id.ctrl);
        recordAudio = (AppCompatButton) findViewById(R.id.recordAudio);
        recordStateView = (MP3RecordStateView) findViewById(R.id.recordStateView);

    }

    @Override
    public void initDatas(JumpParameter parameter) {

        //设置调试模式
        recordStateView.setDebug(true);

    }

    @Override
    public void setEvents() {

        recordAudio.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_DOWN && System.currentTimeMillis() - time < 1000) {
                    log("时间间隔小于1秒，不执行以下代码");
                    return false;
                }

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        v.setPressed(true);

                        //检测录音和文件读写权限
                        if (checkPermissions(
                                new String[]{
                                        Manifest.permission.RECORD_AUDIO,
                                        Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                                })
                        ) {
                            //开始录制
                            recordAudio();
                        } else {
                            requestPermission(new String[]{
                                    Manifest.permission.RECORD_AUDIO,
                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                            }, new OnPermissionResponseListener() {
                                @Override
                                public void onSuccess(String[] permissions) {

                                }

                                @Override
                                public void onFail() {

                                    toast("请赋予权限后再试");

                                }
                            });
                        }

                        return true;
                    case MotionEvent.ACTION_MOVE:
                        if (event.getY() < 0) {
                            recordStateView.showReleaseToCancelHint();
                        } else {
                            recordStateView.showMoveUpToCancelHint();
                        }
                        return true;
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                        v.setPressed(false);
                        isOnTouch = false;
                        if (recordStateView.isRecording()) {
                            if (event.getY() < 0) {
                                //取消录音
                                recordStateView.resolveError();
                            } else {
                                long length = recordStateView.resolveStopRecord();
                                if (length > 1000) {
                                    recordStateView.setVisibility(INVISIBLE);
                                    Message message = new Message();
                                    message.what = MP3Recorder.MESSAGE_FINISH;
                                    message.arg1 = (int) length;
                                    recordStateView.getHandler().sendMessage(message);
                                } else {
                                    recordStateView.showMoveRecordTooShort();

                                    recordStateView.getHandler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            recordStateView.setVisibility(INVISIBLE);
                                        }
                                    }, 1000);
                                }
                            }
                        }
                        return true;
                    default:
                        v.setPressed(false);
                        return false;
                }

            }
        });

        //音频录制回调
        recordStateView.setOnRecordListener(new OnRecordListener() {

            @Override
            public void onNeedPermissions() {

                //检测录音和文件读写权限
                if (checkPermissions(
                        new String[]{
                                Manifest.permission.RECORD_AUDIO,
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                        })
                ) {

                } else {
                    requestPermission(new String[]{
                            Manifest.permission.RECORD_AUDIO,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    }, new OnPermissionResponseListener() {
                        @Override
                        public void onSuccess(String[] permissions) {

                        }

                        @Override
                        public void onFail() {

                            toast("请赋予权限后再试");

                        }
                    });
                }

            }

            @Override
            public void onRecordStart() {
                //录制开始
            }

            @Override
            public void onRecordCancel() {
                //录制取消
            }

            @Override
            public void onRecordError(String errorMsg) {
                //录制异常
                log(errorMsg);
            }

            @Override
            public void onRecordComplete(String filePath_txt, int duration) {
                //录制完成
                filePath.setText("文件地址: "+filePath_txt);
                fileTime.setText("录音时长: "+timeTransverter(duration));
                //准备音频信息
                prepareAudio();
            }
        });

        //播放进度监听
        StarrySky.with().setOnPlayProgressListener(new OnPlayProgressListener() {
            @Override
            public void onPlayProgress(long l, long l1) {

                if (!isUserCtrlSeek) {
                    seek.setMax((int) l1);
                    seek.setProgress((int) l);

                    playTime.setText(timeTransverter(l));
                    mediaTime.setText(timeTransverter(l1));
                }

            }
        });

        //进度条
        seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                if (fromUser) {

                    seek.setProgress(seek.getProgress());

                    playTime.setText(timeTransverter(seek.getProgress()));

                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

                isUserCtrlSeek = true;

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

                isUserCtrlSeek = false;

                StarrySky.with().seekTo(seekBar.getProgress(), true);

            }
        });

        //播放控制
        ctrl.setPlayPauseListener(new PlayPauseView.PlayPauseListener() {
            @Override
            public void play() {
                if (isJustPrepare){
                    StarrySky.with().playMusicByInfo(songInfo);
                    isJustPrepare = false;
                }else {
                    StarrySky.with().restoreMusic();
                }
            }

            @Override
            public void pause() {
                StarrySky.with().pauseMusic();
            }
        });

    }

    /**
     * 音频录制
     */
    private void recordAudio(){

        //释放已存在的音频信息
        releaseAudio();

        //获取文件名
        audioName = TimeUtils.date2Millis(TimeUtils.getNowDate()) + ".mp3";

        //设置录制文件地址
        recordStateView.setFilePath(
                FilePath.AudioRecord + getDateString()+"/",
                audioName);

        isOnTouch = true;
        recordStateView.showMoveUpToCancelHint();
        recordStateView.getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isOnTouch) {
                    time = System.currentTimeMillis();
                    recordStateView.startRecording();
                }
            }
        }, 300);

    }

    /**
     * 获取日期
     *
     * @return 时间戳 例如:201805
     */
    private String getDateString() {
        return DateFormat.format("yyyy-MM-dd", new Date()).toString();
    }

    /**
     * 时间转换
     *
     * @param time Long类型为毫秒数
     */
    private String timeTransverter(long time) {

        String transverterTime = "";

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(TimeUtils.millis2Date(time));

        //余出来的秒数
        long second = calendar.get(Calendar.SECOND);
        //共有多少分钟
        long minute = calendar.get(Calendar.MINUTE);
        //共有多少小时
        long hour = minute / 60;

        //如果总时长大于一小时,则取余数
        if (minute >= 60) {
            minute = minute % 60;
        }

//        Log.d("Gsy_LeLink_Video", "时间取值 hour --> " + hour);
//        Log.d("Gsy_LeLink_Video", "时间取值 minute --> " + minute);
//        Log.d("Gsy_LeLink_Video", "时间取值 second --> " + second);

        if (hour > 0) {
            if (hour >= 10) {
                transverterTime = "" + hour;
            } else {
                transverterTime = "0" + hour;
            }
        }

        if (minute > 0) {

            if (hour > 0) {
                if (minute >= 10) {
                    transverterTime = transverterTime + ":" + minute;
                } else {
                    transverterTime = transverterTime + ":0" + minute;
                }
            } else {
                if (minute >= 10) {
                    transverterTime = "" + minute;
                } else {
                    transverterTime = "0" + minute;
                }
            }

        } else {
            if (hour > 0) {
                transverterTime = transverterTime + ":00";
            } else {
                transverterTime = "00";
            }

        }

        if (second > 0) {

            if (second >= 10) {
                transverterTime = transverterTime + ":" + second;
            } else {
                transverterTime = transverterTime + ":0" + second;
            }

        } else {
            transverterTime = transverterTime + ":00";
        }

        return transverterTime;

    }

    /**
     * 准备播放音频
     */
    private void prepareAudio(){

        songInfo = new SongInfo();
        songInfo.setSongUrl(FilePath.AudioRecord + getDateString()+"/"+audioName);
        songInfo.setSongId(MD5.hexdigest(songInfo.getSongUrl()));
        //设置单曲播放,不循环
        StarrySky.with().setRepeatMode(RepeatMode.REPEAT_MODE_ONE, false);
        StarrySky.with().prepareByInfo(songInfo);
        isJustPrepare = true;

        //播放状态监听
        StarrySky.with().addPlayerEventListener(new OnPlayerEventListener() {
            @Override
            public void onPlaybackStageChange(@NonNull PlaybackStage playbackStage) {

                if (playbackStage.getStage().equals(PlaybackStage.PLAYING)
                        || playbackStage.equals(PlaybackStage.BUFFERING)) {
                    if (!ctrl.isPlaying()) {
                        ctrl.play();
                    }
                } else {
                    if (ctrl.isPlaying()) {
                        ctrl.pause();
                    }
                }

            }
        }, songInfo.getSongId());

        audioMsgLayout.setVisibility(View.VISIBLE);

    }

    /**
     * 释放音频
     */
    private void releaseAudio(){

        audioMsgLayout.setVisibility(View.GONE);

        if (songInfo!=null){
            StarrySky.with().removeSongInfo(songInfo.getSongId());
            StarrySky.with().removePlayerEventListener(songInfo.getSongId());

            playTime.setText("");
            mediaTime.setText("");

            seek.setProgress(0);

            songInfo = null;
        }

    }

    @Override
    protected void onPause() {
        if (StarrySky.with().isPlaying()){
            StarrySky.with().pauseMusic();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (!StarrySky.with().isPlaying()){
            StarrySky.with().restoreMusic();
        }
        super.onResume();
    }

    @Override
    public void onDestroy() {
        if (songInfo!=null){
            StarrySky.with().removeSongInfo(songInfo.getSongId());
            StarrySky.with().removePlayerEventListener(songInfo.getSongId());
        }
        super.onDestroy();
    }

}